package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import pojo.User;
import service.UserService;
import service.UserServiceImpl;
import tools.Constants;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping(value = {"/login.html","/"},method = RequestMethod.GET)
    public String login(){
        return "login";
    }

    @RequestMapping(value = "/dologin.html", method = RequestMethod.POST)
    public String doLogin(@RequestParam String userCode, @RequestParam String userPassword, Model model, HttpServletRequest request, HttpSession session) throws Exception {

        //调用service方法，进行用户匹配
        User user = userService.login(userCode, userPassword);

        if (null != user) {//登录成功
            //放入session
            session.setAttribute(Constants.USER_SESSION, user);
            //页面跳转（frame.jsp）
            return "redirect:/main.html";
        } else {
            //页面跳转（login.jsp）带出提示信息--转发
            user=userService.selectUserCodeExist(userCode);
            if (user==null){
                request.setAttribute("error", "用户不存在");
            }else {
                request.setAttribute("error", "密码不正确");
            }
            return "login";

        }

    }


    @RequestMapping(value = "/main.html")
    public String main() {
        return "frame";
    }

    @RequestMapping("logout.html")
    public String loginout(HttpSession httpSession){
        httpSession.removeAttribute(Constants.USER_SESSION);
        return "login";
    }
}
